package com.yzx.lifeassistants.activity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;

import com.balysv.materialripple.MaterialRippleLayout;
import com.haarman.listviewanimations.swinginadapters.prepared.SwingBottomInAnimationAdapter;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.weiwangcn.betterspinner.library.material.MaterialBetterSpinner;
import com.yzx.lifeassistants.GlobalParams;
import com.yzx.lifeassistants.R;
import com.yzx.lifeassistants.adapter.MyArrayAdapter;
import com.yzx.lifeassistants.adapter.RunningAdapter;
import com.yzx.lifeassistants.base.BaseActivity;
import com.yzx.lifeassistants.bean.RunningInfo;
import com.yzx.lifeassistants.common.CommonConstant;
import com.yzx.lifeassistants.utils.DensityUtils;
import com.yzx.lifeassistants.utils.LogcatUtils;
import com.yzx.lifeassistants.utils.ToastUtils;
import com.yzx.lifeassistants.view.widget.CircularLoadingDialog;

/**
 * @Description: 约跑信息搜索
 * @author: yzx
 * @time: 2016-4-17 下午7:42:59
 */
@SuppressLint("InflateParams")
public class RunningSearchActivity extends BaseActivity implements
		OnClickListener, OnItemClickListener {

	private ImageButton backBtn;// 返回按钮
	private ImageButton moreBtn;// 更多按钮
	private ImageView grayIV;// 灰色条
	private ListView runningLV;// 约跑列表
	private PullToRefreshListView runningPTRLV;// 刷新
	private ILoadingLayout runningILL;// 加载

	private View contentView;// 条件弹框
	private AlertDialog theDialog;// 条件弹框
	private MaterialBetterSpinner isLongSP;// 是否长期选择框
	private MaterialBetterSpinner isMaleSP;// 是否男性选择框
	private MaterialEditText interestET;// 兴趣输入框

	private CircularLoadingDialog dialog;// 加载
	private RunningAdapter adapter;// 约跑列表适配器
	private List<RunningInfo> dataList;// 约跑数据列表
	private List<Boolean> isList;// 是否本人
	private static final int STATE_REFRESH = 0;// 下拉刷新
	private static final int STATE_MORE = 1;// 加载更多
	private int limit = 10; // 每页的数据是10条
	private int curPage = 0; // 当前页的编号，从0开始
	private String isLong = "不限";// 是否长期
	private String isMale = "不限";// 是否为男性
	private String interest = "";// 兴趣

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_running_search);
		initView();
		setListener();
		initSelectDialog();
		initData();

	}

	/**
	 * 
	 * @Description: 初始化控件
	 */
	private void initView() {
		backBtn = (ImageButton) findViewById(R.id.running_search_back_btn);
		moreBtn = (ImageButton) findViewById(R.id.running_search_more_btn);
		grayIV = (ImageView) findViewById(R.id.running_search_gray_iv);
		runningPTRLV = (PullToRefreshListView) findViewById(R.id.running_search_listview);
		runningILL = runningPTRLV.getLoadingLayoutProxy();
		runningILL.setLastUpdatedLabel("");
		runningILL.setPullLabel("继续拖动");
		runningILL.setRefreshingLabel("正在装载数据···");
		runningILL.setReleaseLabel("放开装载更多");
		runningLV = runningPTRLV.getRefreshableView();
	}

	/**
	 * 
	 * @Description: 设置监听
	 */
	private void setListener() {
		backBtn.setOnClickListener(this);
		moreBtn.setOnClickListener(this);
		// 滑动监听
		runningPTRLV.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (firstVisibleItem == 0) {
					runningILL.setLastUpdatedLabel("");
					runningILL.setPullLabel("下拉刷新");
					runningILL.setRefreshingLabel("加载中···");
					runningILL.setReleaseLabel("释放刷新");
				} else if (firstVisibleItem + visibleItemCount == totalItemCount) {
					runningILL.setLastUpdatedLabel("");
					runningILL.setPullLabel("继续拖动");
					runningILL.setRefreshingLabel("正在装载数据···");
					runningILL.setReleaseLabel("放开装载更多");
				}
			}
		});
		// 下拉刷新监听
		runningPTRLV.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				// 下拉刷新(从第一页开始装载数据)
				dialog.show();
				queryRunning(0, STATE_REFRESH);
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				// 上拉加载更多(加载下一页数据)
				dialog.show();
				queryRunning(curPage, STATE_MORE);
			}

		});
		runningLV.setOnItemClickListener(this);
	}

	/**
	 * 
	 * @Description: 初始化选择对话框
	 */
	private void initSelectDialog() {
		// 弹框
		theDialog = new AlertDialog.Builder(this).create();
		theDialog.setCanceledOnTouchOutside(true);
		// 设置能弹出输入法
		theDialog.setView(new EditText(this));
		contentView = LayoutInflater.from(this).inflate(
				R.layout.dialog_running_search, null);
		// 是否长期
		isLongSP = (MaterialBetterSpinner) contentView
				.findViewById(R.id.dialog_running_search_islong_spinner);
		// 是否男性
		isMaleSP = (MaterialBetterSpinner) contentView
				.findViewById(R.id.dialog_running_search_sex_spinner);
		// 兴趣输入框
		interestET = (MaterialEditText) contentView
				.findViewById(R.id.dialog_running_search_interest_et);
		// 设置Spinner的Adapter
		String[] longs = getResources().getStringArray(
				R.array.running_search_is_long);
		List<String> longList = Arrays.asList(longs);
		MyArrayAdapter longAdapter = new MyArrayAdapter(this, longList);
		isLongSP.setAdapter(longAdapter);
		String[] sexs = getResources().getStringArray(
				R.array.running_search_sex);
		List<String> sexList = Arrays.asList(sexs);
		MyArrayAdapter sexAdapter = new MyArrayAdapter(this, sexList);
		isMaleSP.setAdapter(sexAdapter);
		// 设置Padding
		interestET.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		isLongSP.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		isMaleSP.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		// 取消按钮
		Button cancleBtn = (Button) contentView
				.findViewById(R.id.dialog_running_search_cancle_btn);
		// 搜索按钮
		Button confirmBtn = (Button) contentView
				.findViewById(R.id.dialog_running_search_search_btn);
		// 动态特效
		MaterialRippleLayout
				.on(cancleBtn)
				.rippleColor(Color.parseColor(CommonConstant.RIPPLE_COLOR_DARK))
				.rippleAlpha(CommonConstant.RIPPLE_ALPHA).rippleHover(true)
				.create();
		MaterialRippleLayout
				.on(confirmBtn)
				.rippleColor(Color.parseColor(CommonConstant.RIPPLE_COLOR_DARK))
				.rippleAlpha(CommonConstant.RIPPLE_ALPHA).rippleHover(true)
				.create();
		// 取消事件
		cancleBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				theDialog.dismiss();
			}
		});
		// 确定事件
		confirmBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				isLong = isLongSP.getText().toString();
				isMale = isMaleSP.getText().toString();
				interest = interestET.getText().toString();
				if (null == interest || "".equals(interest)) {
					showToast("请输入兴趣内容~", false);
					return;
				}
				theDialog.dismiss();
				queryRunning(0, STATE_REFRESH);
			}

		});
	}

	/**
	 * 
	 * @Description: 初始化数据
	 */
	private void initData() {
		dialog = new CircularLoadingDialog(this);
		dataList = new ArrayList<RunningInfo>();
		isList = new ArrayList<Boolean>();
		adapter = new RunningAdapter(runningLV, this, dataList, isList);
		SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(
				adapter);
		swingBottomInAnimationAdapter.setAbsListView(runningLV);
		runningLV.setAdapter(swingBottomInAnimationAdapter);
		showSelectDialog();
	}

	/**
	 * 
	 * @Description: 显示条件选择框
	 */
	private void showSelectDialog() {
		theDialog.show();
		theDialog.setContentView(contentView);
		theDialog.getWindow().setGravity(Gravity.CENTER);
	}

	/**
	 * 
	 * @Description: 搜索约跑
	 */
	private void queryRunning(int page, final int actionType) {
		dialog.show();
		// 查询条件1 是否长期
		BmobQuery<RunningInfo> isLongQuery = new BmobQuery<RunningInfo>();
		if (null == isLong || "".equals(isLong) || "不限".equals(isLong)) {

		} else if ("是".equals(isLong)) {
			isLongQuery.addWhereEqualTo("isLong", true);
		} else {
			isLongQuery.addWhereEqualTo("isLong", false);
		}
		// 查询条件2 是否男性
		BmobQuery<RunningInfo> isMaleQuery = new BmobQuery<RunningInfo>();
		if (null == isMale || "".equals(isMale) || "不限".equals(isMale)) {

		} else if ("男".equals(isMale)) {
			isMaleQuery.addWhereEqualTo("isMale", true);
		} else {
			isMaleQuery.addWhereEqualTo("isMale", false);
		}
		// 查询条件3 兴趣
		BmobQuery<RunningInfo> interestQuery = new BmobQuery<RunningInfo>();
		interestQuery.addWhereContains("interest", interest);
		// and(条件1,条件2)
		List<BmobQuery<RunningInfo>> andQueries = new ArrayList<BmobQuery<RunningInfo>>();
		andQueries.add(isLongQuery);
		andQueries.add(isMaleQuery);
		BmobQuery<RunningInfo> andQuery = new BmobQuery<RunningInfo>();
		BmobQuery<RunningInfo> contentQuery = andQuery.and(andQueries);
		// and(条件3,and(条件1,条件2))
		List<BmobQuery<RunningInfo>> andAllQueries = new ArrayList<BmobQuery<RunningInfo>>();
		andAllQueries.add(interestQuery);
		andAllQueries.add(contentQuery);
		BmobQuery<RunningInfo> query = new BmobQuery<RunningInfo>();
		query.order("-updatedAt");// 按照修改时间升序
		query.and(andAllQueries);
		query.setLimit(limit);
		query.setSkip(page * limit);
		query.findObjects(this, new FindListener<RunningInfo>() {
			@Override
			public void onSuccess(List<RunningInfo> list) {// 查询成功
				LogcatUtils.i("查询约跑信息成功");
				dialog.dismiss();
				runningPTRLV.setVisibility(View.VISIBLE);
				runningLV.setVisibility(View.VISIBLE);
				// 若list.size()>0只剩一项时删不掉
				if (list.size() > -1) {
					grayIV.setVisibility(View.VISIBLE);
					if (actionType == STATE_REFRESH) {
						// 当是下拉刷新操作时，将当前页的编号重置为0，清空，重新添加
						curPage = 0;
						dataList.clear();
						isList.clear();
					}
					for (RunningInfo info : list) {
						dataList.add(info);
						if (GlobalParams.userInfo.getUsername().equals(
								info.getUsername())) {
							isList.add(true);
						} else {
							isList.add(false);
						}
					}
					// 这里在每次加载完数据后，将当前页码+1
					// 这样在上拉刷新的onPullUpToRefresh方法中就不需要操作curPage了
					curPage++;
				}
				if (actionType == STATE_MORE && list.size() < 1) {
					grayIV.setVisibility(View.VISIBLE);
					showToast("暂时还未有更多的约跑信息~", true);
				}
				if (actionType == STATE_REFRESH && list.size() < 1) {
					grayIV.setVisibility(View.GONE);
					showToast("暂时还未有约跑信息~", true);
				}
				runningPTRLV.onRefreshComplete();
				adapter.notifyDataSetChanged();
			}

			@Override
			public void onError(int code, String message) {// 查询失败
				LogcatUtils.e("查询约跑列表信息失败：" + code + " " + message);
				dialog.dismiss();
				runningPTRLV.setVisibility(View.VISIBLE);
				runningLV.setVisibility(View.VISIBLE);
				switch (code) {
				case 101: {
					if (actionType == STATE_MORE) {
						grayIV.setVisibility(View.VISIBLE);
						showToast("暂时还未有更多的约跑信息~", true);
					}
					if (actionType == STATE_REFRESH) {
						grayIV.setVisibility(View.GONE);
						showToast("暂时还未有约跑信息~", true);
					}
					break;
				}
				case 9010: {// 网络超时
					showToast("网络超时，请检查您的手机网络~", false);
					break;
				}
				case 9016: {// 无网络连接，请检查您的手机网络
					showToast("无网络连接，请检查您的手机网络~", false);
					break;
				}
				default: {
					showToast("查询失败，请刷新重试~", false);
					break;
				}
				}
				runningPTRLV.onRefreshComplete();
				adapter.notifyDataSetChanged();

			}
		});
	}

	/**
	 * 
	 * @Description: 按键监听
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.running_search_back_btn: {// 返回
			finish();
			break;
		}
		case R.id.running_search_more_btn: {// 更多
			showSelectDialog();
			break;
		}
		default:
			break;
		}
	}

	/**
	 * 
	 * @Description: 列表按键监听
	 */
	@Override
	public void onItemClick(AdapterView<?> adapterView, View view,
			int position, long arg3) {
		Intent intent = new Intent(this, RunningInfoActivity.class);
		intent.putExtra("RUNNING_INFO", dataList.get(position - 1));
		startActivity(intent);
	}

	/**
	 * 
	 * @Description: Toast显示信息
	 */
	private void showToast(String message, Boolean isInfo) {
		if (isInfo) {
			ToastUtils.showInfoToast(this, message, R.id.running_search_top_ll);
		} else {
			ToastUtils
					.showAlertToast(this, message, R.id.running_search_top_ll);
		}

	}
}
